<template>
  <div id="wrapper">
    <main>
      <div class="right-side">
        <div class="logo">
          <img alt="Tachikoma" :src="require('../assets/LOGO.png')" />
        </div>
        <div class="doc" style="position:absolute;top:20vh;">
          <div class="title alt">Audio</div>
          <el-button-group style="position:relative;float:left;margin:1vw">
            <el-button
              icon="el-icon-chat-line-round"
              circle
              @click="onStartRecorder()"
            ></el-button>
            <el-button round @click="onStopRecorder()">stop</el-button>
          </el-button-group>
          <el-button
            icon="el-icon-caret-right"
            style="position:relative;float:left;margin:1vw"
            circle
            @click="onPlayer()"
          ></el-button>
          <el-button-group style="position:relative;float:left;margin:1vw">
            <el-button round @click="onPostData()">POST</el-button>
            <el-button round @click="onCutStrByJieba()">CUT</el-button>
          </el-button-group>
          <el-button
            style="position:relative;float:left;margin:1vw"
            round
            @click="onStr2Audio()"
            >To Txt
          </el-button>
        </div>
        <audio
          ref="audio"
          controls
          style="position:absolute;top:50vh;left:6vw;"
          v-if="reloadFlag"
        >
          <!-- <source src="../assets/audio/temp.mp3" type="audio/mpeg"> -->
          <source :src="reAudioSrc" type="audio/wav">
          您的浏览器不支持 audio 元素。
        </audio>
        <div class="txtarea" style="position:absolute;top:60vh">
          <div>{{ redata.result[0] }}</div>
          <div>{{ jiebaCutStr.dataStr }}</div>

          <div class="input">
            <el-input v-model="toAudioStr" placeholder="请输入内容"></el-input>
            <el-button
              style="position:relative;float:left;margin:1vw"
              round
              @click="onSubString()"
              >Submit
            </el-button>
            <a :href="reAudioSrc"  download="" >下载音频</a>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script>
import SystemInformation from './LandingPage/SystemInformation'
// import PCMPlayer from './LandingPage/pcm-player'
import Recorder from 'js-audio-recorder'
import qs from 'qs'
import Base64 from 'js-base64'
// import jieba from 'nodejieba'

export default {
  name: 'landing-page',
  components: { SystemInformation, Recorder, qs, Base64 },
  data () {
    return {
      recorder: null,
      PCMdata: null,
      WAVdata: null,
      token: '',
      expires: null,
      redata: { result: ['你好你好'] },
      blob2Base64Str: null,
      jiebaCutStr: { dataStr: [] },
      toAudioStr: '',
      reaudio: null,
      reAudioSrc: '',
      reloadFlag: true
    }
  },
  created () {
    this.getToken()
  },
  mounted () {},
  methods: {
    async onStartRecorder () {
      if (!this.recorder) {
        this.recorder = new Recorder({
          sampleBits: 16, // 采样位数，支持 8 或 16，默认是16
          sampleRate: 16000, // 采样率，支持 11025、16000、22050、24000、44100、48000，根据浏览器默认值，我的chrome是48000
          numChannels: 1 // 声道，支持 1 或 2， 默认是1
        })
        // this.recorder.onprocess = function(duration) {
        //     // 部分低版本浏览器不支持innerText，改用innerHTML
        //     oTime.innerHTML = duration.toFixed(5);
        // }
      }
      this.recorder.start().then(() => {
        console.log('start')
        // console.log()
      })
    },
    async onStopRecorder () {
      this.recorder.stop()
      console.log('stop')
      this.PCMdata = this.recorder.getPCMBlob()
      this.WAVdata = this.recorder.getWAVBlob()
      // this.recorder.downloadPCM('temp')
      // this.recorder.downloadWAV('temp')
      this.blobToDataURI(this.PCMdata, result => {
        this.blob2Base64Str = result
      })

      // let reader = await (new Response(this.PCMdata)).text()
      // this.blob2Base64Str = Base64.encode(reader)
    },
    async getToken () {
      const params = {
        grant_type: 'client_credentials',
        client_id: 'ZCRueKzVcLw9ysOtlNQd7rf8',
        client_secret: 'RNFtQi4d7FC1IhsPE2WoT2GEaNLNYHIP'
      }
      let result = await new Promise((resolve, reject) => {
        this.$axios
          .post(
            'https://aip.baidubce.com/oauth/2.0/token',
            qs.stringify(params),
            {
              headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
              }
            }
          )
          .then(res => {
            console.log(res)
            resolve(res.data)
          })
          .catch(error => {
            console.log(error)
          })
      })
      console.log(result)
      // 设置token
      this.$store.dispatch('SET_TOKEN', result.access_token)
      this.token = result.access_token
      this.expires = result.expires_in
    },
    onPostData () {
      // console.log(this.blob2Base64Str)
      let data = {
        format: 'pcm',
        rate: 16000,
        dev_pid: 1537,
        channel: 1,
        token: this.token,
        cuid: 'baidu_workshop',
        len: this.PCMdata.size,
        speech: this.blob2Base64Str
      }
      console.log(this.token)
      // console.log(JSON.stringify(data))
      this.$axios
        .post('http://vop.baidu.com/server_api', JSON.stringify(data))
        .then(res => {
          if (res) {
            const result = res.data
            this.redata = result
            console.log(result)
          }
        })
    },
    onPlayer: function () {
      if (this.recorder) {
        this.recorder.play()
      } else {
        alert('Data is NULL!')
      }
    },
    async blobToDataURI (blob, callback) {
      let reader = new FileReader()
      reader.onload = function (e) {
        callback(e.target.result.split('data:;base64,')[1])
      }
      reader.readAsDataURL(blob)
    },
    onCutStrByJieba () {
      // const params = {
      //   jiebaStr: encodeURIComponent(this.redata.result[0])
      // }
      console.log(this.redata.result[0])
      this.$axios
        .get(
          'http://localhost:8444/cut?jiebaStr=' +
            encodeURIComponent(this.redata.result[0])
        )
        .then(res => {
          if (res) {
            this.jiebaCutStr = res.data
          }
        })
    },
    onStr2Audio () {
      let data = {
        tex: this.toAudioStr,
        tok: this.token,
        cuid: 'baidu_workshop',
        ctp: 1,
        lan: 'zh',
        aue: 6
      }
      this.$axios
        .post('http://tsn.baidu.com/text2audio', qs.stringify(data), {
          responseType: 'blob' // 此处防止返回为其他编码，导致处理困难
        })
        .then(res => {
          if (res) {
            const result = res.data
            this.reaudio = result

            console.log(res)
            // 正在处理

            let src = URL.createObjectURL(result)
            console.log(src)
            this.reAudioSrc = src
            // this.$refs.audio.setAttribute('src', src)
            // this.$refs.audio.setAttribute('type', 'audio/wav')
            this.reloadOfPart()
          }
        })
    },
    onSubString () {
      console.log(this.toAudioStr)
    },
    // async dataURLtoBlob (code) {
    //   let contentType = 'wav'
    //   let raw = window.atob(code)
    //   let rawLength = raw.length

    //   let uInt8Array = new Uint8Array(rawLength)

    //   for (let i = 0; i < rawLength; ++i) {
    //     uInt8Array[i] = raw.charCodeAt(i)
    //   }
    //   return new Blob([uInt8Array], { type: contentType })
    // },
    // floatTo16BitPCM (input) {
    //   // console.log(input)
    //   let buffer = new ArrayBuffer(input.byteLength)
    //   let view = new DataView(buffer)
    //   let temp = new Int8Array(input)
    //   for (let i = 0; i < temp.length; i++) {
    //     view.setInt8(temp[i], true)
    //   }
    //   console.log(temp)
    //   return view.buffer
    // },
    reloadOfPart () {
      this.reloadFlag = false
      this.$nextTick(() => {
        this.reloadFlag = true
      })
    }
  },
  destroyed () {
    window.URL.revokeObjectURL(this.reAudioSrc)
  }
}
</script>

<style lang="scss" scoped>
@import url('https://fonts.googleapis.com/css?family=Source+Sans+Pro');

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  font-family: 'Source Sans Pro', sans-serif;
}

#wrapper {
  height: 100vh;
  width: 88vw;
  position: absolute;
  right: 0;
}

#logo {
  height: auto;
  margin-bottom: 20px;
  width: 420px;
}

main {
  display: flex;
  height: 100vh;
  justify-content: space-between;
}

main > div {
  flex-basis: 50%;
}

.title {
  color: #2c3e50;
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 6px;
}

.title.alt {
  font-size: 18px;
  margin-bottom: 10px;
}
.doc {
  height: 25vh;
  width: 70vw;
  left: 6vw;
}
.doc p {
  color: black;
  margin-bottom: 10px;
}

.doc button {
  font-weight: 800;
  cursor: pointer;
  outline: none;
  display: inline-block;
  color: #4fc08d;
  background-color: #fff;
  transition: all 0.15s ease;
  box-sizing: border-box;
  border: 1px solid #4fc08d;
}

.doc button.alt {
  color: #42b983;
  background-color: transparent;
}
.right-side {
  width: 88vw;
  height: 100vh;
}
.txtarea {
  width: 70vw;
  height: 30vh;
  left: 6vw;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
  border-radius: 4px;
  border: 1px solid #ccc;
  div {
    margin: 1vh;
  }
  .input {
    width: 60vw;
  }
}
</style>
